<template>
    <div class="container">
        <el-tag>用户信息管理界面</el-tag><br>
        <el-form :inline="true" class="query-form">
            <el-form-item label="账号 / 姓名">
                <el-input v-model="queryText" placeholder="请输入查询关键字"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="handleQuery" plain>查询</el-button>
            </el-form-item>
        </el-form>

        <el-button type="primary" class="add-button" @click="showAddDialog">
            新增
        </el-button>

        <el-table :data="filteredData" border class="center-table">
            <!-- 表格列 -->
            <el-table-column label="编号" width="60">
                <template slot-scope="scope">
                    <!-- 使用 v-for 指令和索引显示编号 -->
                    <span :index="scope.$index + 1">{{ scope.$index + 1 }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="account" label="账号"></el-table-column>
            <el-table-column prop="password" label="密码"></el-table-column>
            <el-table-column prop="fullname" label="姓名"></el-table-column>
            <el-table-column prop="sex" label="性别" width="100">
                <!-- 使用条件渲染显示不同的标签 -->
                <template slot-scope="scope">
                    <span v-if="scope.row.sex === '男'"><el-tag>男</el-tag></span>
                    <span v-else-if="scope.row.sex === '女'"><el-tag type="danger">女</el-tag></span>
                    <span v-else-if="scope.row.sex === '保密'"><el-tag type="success">保密</el-tag></span>
                </template>
            </el-table-column>
            <el-table-column prop="role" label="角色" width="120"></el-table-column>
            <el-table-column prop="phone" label="手机号码" width="140"></el-table-column>
            <el-table-column prop="email" label="邮箱"></el-table-column>
            <el-table-column prop="status" label="状态" width="100">
                <template slot-scope="scope">
                    <span v-if="scope.row.status === '启用'"><el-tag type="success">启用</el-tag></span>
                    <span v-else-if="scope.row.status === '禁用'"><el-tag type="danger">禁用</el-tag></span>
                </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注"></el-table-column>

            <!-- 编辑按钮列 -->
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <el-button type="primary" plain size="small" @click="showEditDialog(scope.row)">
                        编辑
                    </el-button>
                    <el-button type="danger" plain size="small" @click="handleDelete(scope.row)">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination style="margin-top: 20px;" :current-page="currentPage" :page-size="pageSize" :total="totalRows"
            @current-change="handlePageChange"></el-pagination>

        <!-- 新增弹窗 -->
        <el-dialog title="新增用户信息" :visible="isAddDialogVisible" :scrollable="false" @close="resetAddDialog" width="800px">
            <el-form ref="addForm" :model="addForm" label-width="80px" style="padding: 0px 50px;">
                <el-form-item label="账号" required>
                    <el-input v-model="addForm.account"></el-input>
                </el-form-item>
                <el-form-item label="密码" required>
                    <el-input v-model="addForm.password" show-password></el-input>
                </el-form-item>
                <el-form-item label="姓名" required>
                    <el-input v-model="addForm.fullname"></el-input>
                </el-form-item>
                <el-form-item label="性别" required>
                    <el-select v-model="addForm.sex" placeholder="请选择" style="width: 100%;">
                        <el-option label="男" value="男"></el-option>
                        <el-option label="女" value="女"></el-option>
                        <el-option label="保密" value="保密"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="角色" required>
                    <el-select v-model="addForm.role" placeholder="请选择" style="width: 100%;">
                        <el-option label="超级管理员" value="超级管理员"></el-option>
                        <el-option label="管理员" value="管理员"></el-option>
                        <el-option label="普通用户" value="普通用户"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="手机号码" required>
                    <el-input v-model="addForm.phone" maxlength="11"></el-input>
                </el-form-item>
                <el-form-item label="邮箱">
                    <el-input v-model="addForm.email"></el-input>
                </el-form-item>
                <el-form-item label="状态" required>
                    <el-select v-model="addForm.status" placeholder="请选择" style="width: 100%;">
                        <el-option label="启用" value="启用"></el-option>
                        <el-option label="禁用" value="禁用"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input v-model="addForm.remark"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer">
                <el-button @click="resetAddDialog">取消</el-button>
                <el-button type="primary" @click="handleAdd">提交</el-button>
            </div>
        </el-dialog>

        <!-- 编辑弹窗 -->
        <el-dialog title="编辑用户信息" :visible="isEditDialogVisible" :scrollable="false" @close="resetEditDialog" width="800px">
            <el-form ref="editForm" :model="editForm" label-width="80px" style="padding: 0px 50px;">
                <el-form-item label="账号">
                    <el-input v-model="editForm.account" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="密码" required>
                    <el-input v-model="editForm.password" show-password></el-input>
                </el-form-item>
                <el-form-item label="姓名" required>
                    <el-input v-model="editForm.fullname"></el-input>
                </el-form-item>
                <el-form-item label="性别" required>
                    <el-select v-model="editForm.sex" placeholder="请选择" style="width: 100%;">
                        <el-option label="男" value="男"></el-option>
                        <el-option label="女" value="女"></el-option>
                        <el-option label="保密" value="保密"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="角色" required>
                    <el-select v-model="editForm.role" placeholder="请选择" style="width: 100%;">
                        <el-option label="超级管理员" value="超级管理员"></el-option>
                        <el-option label="管理员" value="管理员"></el-option>
                        <el-option label="普通用户" value="普通用户"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="手机号码" required>
                    <el-input v-model="editForm.phone" maxlength="11"></el-input>
                </el-form-item>
                <el-form-item label="邮箱">
                    <el-input v-model="editForm.email"></el-input>
                </el-form-item>
                <el-form-item label="状态" required>
                    <el-select v-model="editForm.status" placeholder="请选择" style="width: 100%;">
                        <el-option label="启用" value="启用"></el-option>
                        <el-option label="禁用" value="禁用"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input v-model="editForm.remark"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer">
                <el-button @click="resetAddDialog">取消</el-button>
                <el-button type="primary" @click="handleEdit">提交</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
import axios from 'axios';

export default {
    data() {
        return {
            isAdmin: false,
            queryText: '', // 查询关键字
            tableData: [], // 所有数据
            filteredData: [], // 过滤后的数据
            isAddDialogVisible: false, // 新增弹窗是否显示
            isEditDialogVisible: false, // 编辑弹窗是否显示
            addForm: { // 新增表单数据
                account: '',
                password: '',
                fullname: '',
                sex: '',
                role: '',
                phone: '',
                email: '',
                status: '',
                remark: '',
            },
            editForm: { // 编辑表单数据
                account: '',
                password: '',
                fullname: '',
                sex: '',
                role: '',
                phone: '',
                email: '',
                status: '',
                remark: '',
            },
            currentPage: 1, // 当前页码
            pageSize: 10, // 每页显示的行数
            totalRows: 0, // 总行数
        };
    },
    mounted() {
        if (!localStorage.getItem('users')) {
            this.$router.push("/");
            this.$message({
                message: '用户未登录！非法操作！',
                type: 'error'
            });
        }
        this.getData();
    },
    methods: {
        getData() {
            // 发送请求获取数据，例如使用axios或其他方式
            axios.get('http://localhost:8888/users/get')
                .then(response => {
                    // 处理请求成功情况
                    console.log('获取数据成功');
                    this.tableData = response.data; // 将获取到的数据赋值给tableData
                    this.totalRows = this.tableData.length; // 设置总行数
                    this.filteredData = this.tableData.slice(
                        (this.currentPage - 1) * this.pageSize,
                        this.currentPage * this.pageSize
                    ); // 初始化filteredData，根据当前页码和每页显示的行数进行切片
                })
                .catch(error => {
                    // 处理请求错误
                    console.error(error);
                });
        },

        handleQuery() {
            this.filteredData = this.tableData.filter(item => {
                // 根据查询关键字过滤数据
                return item.account.includes(this.queryText) || item.fullname.includes(this.queryText);
            });
        },

        showAddDialog() {
            this.isAddDialogVisible = true; // 显示新增弹窗
        },

        resetAddDialog() {
            this.isAddDialogVisible = false;
            this.$refs.addForm.resetFields(); // 重置新增表单
        },

        handleAdd() {

            if (!this.addForm.account || !this.addForm.password || !this.addForm.fullname || !this.addForm.role || !this.addForm.sex || !this.addForm.phone || !this.addForm.status
            ) {
                this.$message({
                    type: 'error',
                    message: '必填项不能为空！'
                });
                return false;
            }
            else if (!/^1[3456789]\d{9}$/.test(this.addForm.phone)) {
                this.$message({
                    type: 'error',
                    message: '请输入正确的手机号！'
                });
                return false;
            }
            else if (this.addForm.email && !/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(this.addForm.email)) {
                this.$message({
                    type: 'error',
                    message: '请输入正确的邮箱！'
                });
                return false;
            }

            // 检查账号是否已存在
            const accountExists = this.tableData.some(item => item.account === this.addForm.account);
            if (accountExists) {
                this.$message({
                    type: 'error',
                    message: '账号已存在！请输入新的账号！'
                });
                return false;
            }
            axios
                .post('http://localhost:8888/users/add', this.addForm)
                .then(response => {
                    // 处理新增成功情况
                    this.$message({
                        type: 'success',
                        message: '新增成功！'
                    });

                    this.getData();
                    this.isAddDialogVisible = false;
                    // 刷新数据

                    this.handleQuery();
                    this.getData();
                    // 关闭弹窗
                    this.resetAddDialog();
                })
                .catch(error => {
                    // 处理请求错误
                    console.error(error);
                });
        },

        showEditDialog(row) {
            this.editForm = Object.assign({}, row); // 将当前行的数据复制到编辑表单
            this.isEditDialogVisible = true; // 显示编辑弹窗
        },

        resetEditDialog() {
            this.isEditDialogVisible = false;
            this.$refs.editForm.resetFields(); // 重置编辑表单
        },

        handleEdit() {
            if (!this.editForm.account || !this.editForm.password || !this.editForm.fullname || !this.editForm.role || !this.editForm.sex || !this.editForm.phone || !this.editForm.status
            ) {
                this.$message({
                    type: 'error',
                    message: '必填项不能为空！'
                });
                return false;
            }
            else if (!/^1[3456789]\d{9}$/.test(this.editForm.phone)) {
                this.$message({
                    type: 'error',
                    message: '请输入正确的手机号！'
                });
                return false;
            }
            else if (this.editForm.email && !/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(this.editForm.email)) {
                this.$message({
                    type: 'error',
                    message: '请输入正确的邮箱！'
                });
                return false;
            }
            axios
                .put(`http://localhost:8888/users/update/${this.editForm.id}`, this.editForm)
                .then(response => {
                    this.$message({
                        type: 'success',
                        message: '编辑成功！'
                    });
                    this.getData();
                    this.handleQuery();
                    // 关闭弹窗
                    this.resetEditDialog();
                })
                .catch(error => {
                    // 处理请求错误
                    console.error(error);
                });
        },
        handleDelete(row) {
            // 弹窗确认是否删除
            this.$confirm('确定删除该用户吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(() => {
                    // 发送删除请求
                    axios.delete(`http://localhost:8888/users/delete/${row.id}`)
                        .then(response => {
                            this.$message({
                                type: 'success',
                                message: '删除成功！'
                            });
                            this.getData();
                        })
                        .catch(error => {
                            // 处理请求错误
                            console.error(error);
                        });
                })
                .catch(() => {
                    // 取消删除操作
                    console.log('取消删除');
                });
        },
        handlePageChange(currentPage) {
            this.currentPage = currentPage; // 更新当前页码
            this.filteredData = this.tableData.slice(
                (this.currentPage - 1) * this.pageSize,
                this.currentPage * this.pageSize
            ); // 根据新的页码进行数据切片
        },

    }
};
</script>

<style>
.container {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
}

.add-button {
    margin-bottom: 10px;
}

.query-form .el-form-item {
    margin-right: 10px;
}

.el-table .warning-row {
    background: oldlace;
}

.el-table .success-row {
    background: #f0f9eb;
}

.center-table .cell {
    text-align: center;
}
</style>
